package org.elec.mac.wx;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.Calendar;

@Component
@Slf4j
public class AccessTokenTask {

    public static AccessToken accessToken = null;

    @Value("${tencent.wx.tokenurl}")
    private String tokenurl;

    @Value("${tencent.wx.appid}")
    private String appid;

    @Value("${tencent.wx.secret}")
    private String secret;

    @Value("${tencent.wx.jsapiurl}")
    private String jsapiurl;

    /**
     *
     */
    @Scheduled(fixedDelay = 3000)
    private void tokenHandler() {
        if(accessToken != null) {
            try {
                //log.info("Wx AccessToken Start");
                Long expires_in = accessToken.getExpires_in() * 1000;
                Long current_in = Calendar.getInstance().getTimeInMillis();
                if(current_in - accessToken.getLogin_time() > expires_in) {
                    accessToken = this.wxAuthToken();
                    log.info("[access_token]:" + accessToken.getAccess_token());
                    log.info("[ticket]:" + accessToken.getTicket());
                }
                //log.info("Wx AccessToken Stop");
            } catch(Exception ex) {
                log.error("微信AccessToken分析错误", ex);
            }
        } else {
            accessToken = this.wxAuthToken();
            log.info("[access_token]:" + accessToken.getAccess_token());
            log.info("[ticket]:" + accessToken.getTicket());
        }
    }

    /**
     * @return
     */
    private AccessToken wxAuthToken() {
        AccessToken accessToken = new AccessToken();
        try {
            OkHttpClient httpClient = new OkHttpClient();
            RequestBody body = new FormBody.Builder()
                    .add("appid", appid).add("secret", secret)
                    .add("grant_type", "client_credential").build();
            Request req = new Request.Builder().url(tokenurl).post(body).build();
            Response resp = httpClient.newCall(req).execute();
            if(resp.isSuccessful()) {
                JSONObject responseBody = new JSONObject(resp.body().string());
                accessToken.setAccess_token(responseBody.getString("access_token"));
                accessToken.setExpires_in(Long.parseLong(responseBody.get("expires_in").toString()));
                accessToken.setLogin_time(Calendar.getInstance().getTimeInMillis());

                body = new FormBody.Builder().add("access_token", accessToken.getAccess_token())
                        .add("type", "jsapi").build();
                req = new Request.Builder().url(jsapiurl).post(body).build();
                resp = httpClient.newCall(req).execute();

                if(resp.isSuccessful()) {
                    JSONObject responseBody2 = new JSONObject(resp.body().string());
                    accessToken.setTicket(responseBody2.getString("ticket"));
                }

            } else {
                accessToken = null;
            }
        } catch(Exception ex) {
            log.error("微信获取JS-SDK鉴权信息错误", ex);
            accessToken = null;
        }
        return accessToken;
    }
}
